//创建仓库
export const createStore = (reducer)=>{
    //定义一个状态
    let state;
    //用于储存监听函数数组
    let listeners = [];
    //留用接口用来随时获取最新的状态
    let getState = ()=>state;
    //留用接口用来向仓库发送action(派发)，改变状态
    let dispatch = (action)=>{
        //传入老的state和action，返回新的state
        state = reducer(state,action);
        //依次遍历并调用储存的订阅函数
        listeners.forEach(listener=>listener());
        //返回新的state
        return state
    };
    //订阅仓库内的状态变化事件，当状态发生变化之后会调用对应的监听函数
    //订阅方法执行后会返回一个取消订阅的函数，调用它可以取消订阅
    let subscribe = (listener)=>{
        //添加监听者
        listeners.push(listener);
        //再添加完监听后，会返回一个取消订阅的函数，subscribe再次调用会移除该监听
        //实现了一个函数两用的作用
        return ()=>{
            listeners = listeners.filter(l=>listener!==l);
        }
    };
    //首次自调用，用于获取默认state值
    dispatch();
    return {
        getState,
        subscribe,
        dispatch
    }
}
export const createStore2 = (reducer) => {
    let state
    let listeners = []
    function getState () {
        return state
    }
    function dispatch (action) {
        state = reducer(state,action)
        listeners.forEach(fn => {
            fn()
        })
        return state
    }
    function subscribe (fn) {
        listeners.push(fn)
        return () => {
            listeners = listeners.filter(item => item!=fn)
        }
    }
    return {
        getState,
        dispatch,
        subscribe,
    }
}